package com.shop.cereshop.commons.tencent.im.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.shop.cereshop.commons.domain.express.HttpResult;
import com.shop.cereshop.commons.domain.im.tx.req.ImBaseModel;
import com.shop.cereshop.commons.domain.im.tx.req.enums.ReqUrlEnums;
import com.shop.cereshop.commons.tencent.im.constant.CustomMsgModelType;
import com.shop.cereshop.commons.tencent.im.constant.SyncOtherMachine;
import com.shop.cereshop.commons.tencent.im.enums.im.ActionStatus;
import com.shop.cereshop.commons.tencent.im.enums.im.MsgTypeEnum;
import com.shop.cereshop.commons.tencent.im.factory.MessageElementFactory;
import com.shop.cereshop.commons.tencent.im.model.msg.data.CustomMsgData;
import com.shop.cereshop.commons.tencent.im.model.msg.data.CustomMsgDataModel;
import com.shop.cereshop.commons.tencent.im.model.msg.data.MsgData;
import com.shop.cereshop.commons.tencent.im.model.msg.dto.MsgRequestDTO;
import com.shop.cereshop.commons.tencent.im.model.msg.element.TIMMsgElement;
import com.shop.cereshop.commons.tencent.im.model.request.*;
import com.shop.cereshop.commons.tencent.im.model.response.SendGroupMsgResponse;
import com.shop.cereshop.commons.tencent.im.model.response.SendMsgResponse;
import com.shop.cereshop.commons.tencent.im.model.response.TIMBaseResponse;
import com.shop.cereshop.commons.tencent.im.service.TimMsgService;
import com.shop.cereshop.commons.tencent.im.utils.JsonUtils;
import com.shop.cereshop.commons.utils.HttpUtils;
import com.shop.cereshop.commons.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @description: 腾讯云IM 消息接口实现
 * @author zdd
 * @date 2025/9/3 14:30
 * @version 1.0
 */
@Slf4j
@Service
public class TimMsgServiceImpl implements TimMsgService {

    /**
     * 消息离线保存时长（单位：秒），最长为7天（604800秒）
     */
    public static final int MSG_LIFE_TIME = 604800;

    @Resource
    private ImBaseModel imBaseModel;
    @Resource
    private MessageElementFactory messageElementFactory;

    @Override
    public SendMsgResponse sendC2cMsg(MsgTypeEnum msgType, MsgData msgData, MsgRequestDTO requestDTO) {
        log.info("发送单聊消息, requestDTO: {}", JSONObject.toJSONString(requestDTO));
        try {
            TIMMsgElement msgElement = messageElementFactory.buildMsgElement(msgType, msgData);
            if (msgElement == null) {
                log.error("构建单发单聊消息元素失败");
                return new SendMsgResponse(ActionStatus.FAIL.getStatus(), "", -1);
            }
            return sendC2cMsg(msgElement, requestDTO);
        } catch (Exception e) {
            log.error("单发单聊消息失败", e);
            return new SendMsgResponse(ActionStatus.FAIL.getStatus(), "", -1);
        }
    }

    @Override
    public SendMsgResponse sendC2cMsg(TIMMsgElement msgElement, MsgRequestDTO requestDTO) {
        try {
            int msgTimeStamp = (int) (System.currentTimeMillis() / 1000);
            List<TIMMsgElement> msgBody = Collections.singletonList(msgElement);
            SendC2cMsgRequest sendC2cMsgRequest = SendC2cMsgRequest.builder()
                    .fromAccount(requestDTO.getFromAccount())
                    .toAccount(requestDTO.getToAccount())
                    .msgRandom(RandomUtil.nextLong())
                    .msgBody(msgBody)
                    .syncOtherMachine(SyncOtherMachine.YES)
                    .msgTimeStamp(msgTimeStamp)
                    .msgLifeTime(MSG_LIFE_TIME)
                    .build();
            imBaseModel.setReqMethod(ReqUrlEnums.SINGLE_SEND_MSG.getUrl());
            HttpResult result = HttpUtils.doPostJson(imBaseModel.toString(), JSONObject.toJSON(sendC2cMsgRequest));
            log.info("单发单聊消息结果：{}", JSONObject.toJSONString(result));
            if (result.getStatus() == 200) {
                return JsonUtils.fromJson(result.getBody(), SendMsgResponse.class);
            } else {
                return new SendMsgResponse(ActionStatus.FAIL.getStatus(), "", -1);
            }
        } catch (Exception e) {
            log.error("单发单聊消息失败", e);
            return new SendMsgResponse(ActionStatus.FAIL.getStatus(), "", -1);
        }
    }

    @Override
    public SendGroupMsgResponse sendGroupMsg(MsgTypeEnum msgType, MsgData msgData, MsgRequestDTO requestDTO) {
        log.info("发送群聊消息, requestDTO: {}", JSONObject.toJSONString(requestDTO));
        try {
            TIMMsgElement msgElement = messageElementFactory.buildMsgElement(msgType, msgData);
            if (msgElement == null) {
                log.error("构建群聊消息元素失败");
                return new SendGroupMsgResponse(ActionStatus.FAIL.getStatus(), "", -1);
            }
            OfflinePushInfo offlinePushInfo = OfflinePushInfo.builder()
                    .pushFlag(0)
                    .title(requestDTO.getTitle())
                    .desc(requestDTO.getDesc())
                    .build();
            List<TIMMsgElement> msgBody = Collections.singletonList(msgElement);
            SendGroupMsgRequest sendMsgRequest = SendGroupMsgRequest.builder()
                    .fromAccount(requestDTO.getFromAccount())
                    .groupId(requestDTO.getGroupId())
                    .random(RandomUtil.nextLong())
                    .msgBody(msgBody)
                    .msgPriority("Normal")
                    .offlinePushInfo(offlinePushInfo)
                    .onlineOnlyFlag(0)
//                    .groupAtInfos()
                    .build();
            imBaseModel.setReqMethod(ReqUrlEnums.GROUP_SEND_MSG.getUrl());
            HttpResult result = HttpUtils.doPostJson(imBaseModel.toString(), JSONObject.toJSON(sendMsgRequest));
            log.info("发送群聊消息结果：{}", JSONObject.toJSONString(result));
            if (result.getStatus() == 200) {
                return JsonUtils.fromJson(result.getBody(), SendGroupMsgResponse.class);
            } else {
                return new SendGroupMsgResponse(ActionStatus.FAIL.getStatus(), "", -1);
            }
        } catch (Exception e) {
            log.error("发送群聊消息失败", e);
            return new SendGroupMsgResponse(ActionStatus.FAIL.getStatus(), "", -1);
        }
    }

    @Override
    public TIMBaseResponse modifyC2cMsg(MsgTypeEnum msgType, MsgData msgData, MsgRequestDTO requestDTO) {
        log.info("修改单聊历史消息, requestDTO: {}", JSONObject.toJSONString(requestDTO));
        try {
            TIMMsgElement msgElement = messageElementFactory.buildMsgElement(msgType, msgData);
            if (msgElement == null) {
                log.error("构建修改单聊历史消息元素失败");
                return new TIMBaseResponse(ActionStatus.FAIL.getStatus(), "", -1);
            }
            List<TIMMsgElement> msgBody = Collections.singletonList(msgElement);
            ModifyC2cMsgRequest sendC2cMsgRequest = ModifyC2cMsgRequest.builder()
                    .fromAccount(requestDTO.getFromAccount())
                    .toAccount(requestDTO.getToAccount())
                    .msgKey(requestDTO.getMsgKey())
                    .msgBody(msgBody)
                    .cloudCustomData(requestDTO.getCloudCustomData())
                    .build();
            imBaseModel.setReqMethod(ReqUrlEnums.MODIFY_C2C_MSG.getUrl());
            HttpResult result = HttpUtils.doPostJson(imBaseModel.toString(), JSONObject.toJSON(sendC2cMsgRequest));
            log.info("修改单聊历史消息消息结果：{}", JSONObject.toJSONString(result));
            if (result.getStatus() == 200) {
                return JsonUtils.fromJson(result.getBody(), SendMsgResponse.class);
            } else {
                return new TIMBaseResponse(ActionStatus.FAIL.getStatus(), "", -1);
            }
        } catch (Exception e) {
            log.error("修改单聊历史消息失败", e);
            return new TIMBaseResponse(ActionStatus.FAIL.getStatus(), "", -1);
        }
    }

    @Override
    public TIMBaseResponse modifyGroupMsg(MsgTypeEnum msgType, MsgData msgData, MsgRequestDTO requestDTO) {
        log.info("修改群聊历史消息, requestDTO: {}", JSONObject.toJSONString(requestDTO));
        try {
            TIMMsgElement msgElement = messageElementFactory.buildMsgElement(msgType, msgData);
            if (msgElement == null) {
                log.error("构建修改群聊历史消息元素失败");
                return new TIMBaseResponse(ActionStatus.FAIL.getStatus(), "", -1);
            }
            List<TIMMsgElement> msgBody = Collections.singletonList(msgElement);
            ModifyGroupMsgRequest sendMsgRequest = ModifyGroupMsgRequest.builder()
                    .groupId(requestDTO.getGroupId())
                    .msgSeq(requestDTO.getMsgSeq())
                    .topicId(requestDTO.getTopicId())
                    .msgBody(msgBody)
                    .cloudCustomData(requestDTO.getCloudCustomData())
                    .build();
            imBaseModel.setReqMethod(ReqUrlEnums.MODIFY_GROUP_MSG.getUrl());
            HttpResult result = HttpUtils.doPostJson(imBaseModel.toString(), JSONObject.toJSON(sendMsgRequest));
            log.info("修改群聊历史消息结果：{}", JSONObject.toJSONString(result));
            if (result.getStatus() == 200) {
                return JsonUtils.fromJson(result.getBody(), SendGroupMsgResponse.class);
            } else {
                return new TIMBaseResponse(ActionStatus.FAIL.getStatus(), "", -1);
            }
        } catch (Exception e) {
            log.error("修改群聊历史消息失败", e);
            return new TIMBaseResponse(ActionStatus.FAIL.getStatus(), "", -1);
        }
    }

    @Override
    public SendMsgResponse sendDisableUserImNotice(Long receiverId, String status) {
        CustomMsgDataModel<Object> dataModel = new CustomMsgDataModel<>(CustomMsgModelType.ON_OR_OFF_USER_IM, status);
        CustomMsgData customMsgData = CustomMsgData.builder()
                .data(JSON.toJSONString(dataModel))
                .build();
        MsgRequestDTO requestDTO = MsgRequestDTO.builder()
                .fromAccount("sendSignal")
                .toAccount(String.valueOf(receiverId))
                .build();
        return sendC2cMsg(MsgTypeEnum.CUSTOM, customMsgData, requestDTO);
    }

}
